<template>
    <el-container class="buy_return_bill_form_container">
        <el-main>
            <el-card class="box-card">
                <div slot="header" class="clearfix" style="padding-left: 0;"
                     v-contraction="{close:dialog, click: contractionClick('buyReturnBillFormTableRef')}">
                    <el-form ref="buyReturnBillForm" :rules="rules" :model="formData" label-width="100px"
                             v-enterToNext>
                        <el-row :gutter="15">
                            <el-col :span="8">
                                <el-form-item label="供应商" prop="supplier_sid">
                                    <vSelectBottom v-model="formData.supplier_sid" type="supplierDrawer"
                                                   @event="handleSupplierEvent" :options="supplierOptions"
                                                   :disabled="disabledSupplier" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="退货日期" prop="return_date">
                                    <el-date-picker v-model="formData.return_date" type="date"
                                                    value-format="yyyy-MM-dd"
                                                    :disabled="!isEditFlag" style="width: 100%;" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="退货单号" prop="code">
                                    <el-input v-model="formData.code" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="供应商联系人" prop="supplier_contract_name">
                                    <el-input v-model="formData.supplier_contract_name" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="供应商联系电话" prop="supplier_contract_phone">
                                    <el-input v-model="formData.supplier_contract_phone" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="发货方式" prop="delivery_mode">
                                    <el-input v-model="formData.delivery_mode" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="预估运费" prop="pre_freight">
                                    <el-input v-model="formData.pre_freight" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="实付运费" prop="real_freight">
                                    <el-input v-model="formData.real_freight" autocomplete="off" clearable
                                              :disabled="!isEditFlag" @change="calcShouldReturnAmount()"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="包邮" prop="free_shipping">
                                    <el-checkbox v-model="formData.free_shipping" :true-label="1" :false-label="0"
                                                 :disabled="!isEditFlag" @change="calcShouldReturnAmount()" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="应退金额" prop="should_return_amount">
                                    <el-input v-model="formData.should_return_amount" autocomplete="off" clearable
                                              :disabled="!isEditFlag" readonly placeholder="自动计算"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="抹零" prop="ignore_amount">
                                    <el-input v-model="formData.ignore_amount" autocomplete="off" clearable
                                              :disabled="!isEditFlag" v-double-input="{ len: 4, negative: false }"
                                              @change="calcShouldReturnAmount()" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="已退金额" prop="return_amount">
                                    <el-input v-model="formData.return_amount" autocomplete="off" clearable
                                              :disabled="!isEditFlag" v-double-input="{ len: 4, negative: false }" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="备注" prop="note_info">
                                    <el-input v-model="formData.note_info" autocomplete="off" clearable
                                              :disabled="!isEditFlag"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="card_content">
                    <div class="btn_container" v-if="isEditFlag && !buy">
                        <el-button type="success" size="mini" @click="handleSelectBuyOrder">选单</el-button>
                    </div>
                    <vxeTableTemplate ref="buyReturnBillFormTableRef" :data="dataList" :options.sync="tableOptions" />
                </div>
            </el-card>
        </el-main>
        <el-footer class="card-foot" height="50px" v-if="!dialog">
            <el-button size="medium" @click="toBack()">返回</el-button>
            <el-button type="primary" size="medium" @click="confirm()" v-if="isEditFlag">确定</el-button>
        </el-footer>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import JxcDialogBase from "@jxc/mixins/JxcDialogBase";
import clothing from "@jxc/utils/clothing";
import SelectBuyOrderDetail from "./SelectBuyOrderDetail";

export default {
    extends: JxcDialogBase,
    name: "BuyReturnBillForm",
    props: {
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
        buy: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        const _this = this;
        return {
            formData: {},
            rules: {
                code: [
                    { required: true, message: "请输入退货单号", trigger: "blur" },
                    { max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur", },
                ],
                return_date: [
                    { required: true, message: "请选择退货日期", trigger: "change" },
                ],
                supplier_sid: [
                    { required: true, message: "请选择供应商", trigger: "change" },
                ],
            },
            supplierOptions: {
                disabled: true,
                placeholder: '请选择供应商',
                bottomAction: {
                    permission: 'save_sys_supplier',
                    permissionUrl: '/sysSupplier',
                },
            },
            dataList: [],
            tableOptions: {
                ref: "JxcSaleReturnBillDialogTable",
                container: ".buy_return_bill_form_container",
                keepSource: true,
                editConfig: {
                    trigger: "click",
                    mode: "cell",
                    showStatus: true,
                },
                editRules: {
                    qty: [
                        {required: true, message: '请输入'},
                    ],
                    unit_name: [
                        {required: true, message: '请选择'},
                    ],
                    price: [
                        {required: true, message: '请输入'},
                    ],
                },
                showSummary: true,
                summaryArray: [ 'qty', 'amount' ],
                columns: [],
                baseColumns: [
                    {
                        label: "采购单号",
                        prop: "order_code",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "规格",
                        prop: "spec_info",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "数量",
                        prop: "qty",
                        align: "center",
                        minWidth: 120,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 3,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: "单位",
                        prop: "unit_name",
                        align: "center",
                        minWidth: 90,
                        editRender: {
                            name: "CustomSelect",
                            autoselect: true,
                            props: {
                                filterable: true,
                                clearable: true,
                                dataMethod(row) {
                                    return (row.price_list || []).map(item => {
                                        return {
                                            label: item.unit_name,
                                            value: item.unit_name,
                                        };
                                    });
                                },
                            },
                            events: {
                                change: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: "基本数量",
                        prop: "qty4base",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "采购单价",
                        prop: "price",
                        align: "center",
                        minWidth: 100,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return _this.$utils.isNotEmpty(row.goods_sid);
                            },
                        },
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                    },
                    {
                        label: "金额",
                        prop: "amount",
                        align: "center",
                        minWidth: 120,
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "未退货基本数量",
                        prop: "remain_qty4base",
                        align: "center",
                        minWidth: 90,
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "center",
                        minWidth: 90,
                        editRender: {
                            name: "CustomInput",
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            size: 'mini',
                            type: 'danger',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                let dataList = _this.dataList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.dataList = _this.resetIndex(dataList);
                            }
                        }
                    ],
                },
                pagination: false,
            },
        };
    },
    computed: {
        ...mapState('jxc', ['setting']),
        isEditFlag() {
            if (this.detail) {
                return false;
            }
            return this.$utils.isEmpty(this.formData.audit_state) || this.formData.audit_state === 0;
        },
        disabledSupplier() {
            if (this.buy) {
                return true;
            }
            return !this.isEditFlag;
        },
        formTableRef() {
            return this[this.tableOptions.ref];
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
        dataList: {
            handler() {
                this.calcShouldReturnAmount();
            },
            deep: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            if (_this.detail) {
                _this.rules = {};
            }
            await _this.storeDispatch('jxc/initSetting');
            _this.initTableOptions();
            if (_this.$refs.buyReturnBillForm) {
                _this.$refs.buyReturnBillForm.clearValidate();
            }
            if (_this.buy) {
                _this.initData4Buy(_this.row.sid);
            } else {
                if (_this.$utils.isNotEmpty(_this.row.sid)) {
                    await _this.initData(_this.row.sid);
                } else {
                    _this.formData = {
                        return_date: _this.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
                    };
                    _this.generateCode();
                }
            }
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = clothing.resetTableColumns(_this.setting, columns, 'qty', (row, column) => {
                let { params } = column;
                let keys = Object.keys(row.preset_buy_map || {});
                return keys.indexOf(params.label) !== -1;
            });
            let operates = $.extend({}, _this.tableOptions.operates);
            if (!_this.isEditFlag) {
                columns = columns.map(item => {
                    let obj = $.extend({}, item);
                    delete obj.editRender;
                    return obj;
                });
                operates = {};
            }
            if (!_this.isEditFlag) {
                columns = columns.filter(item => item.prop !== 'remain_qty4base');
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns, operates,
                getMaxHeight: !_this.dialog ? undefined : () => {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            });
        },
        initData4Buy(sid) {
            const _this = this;
            _this.dataList = [];
            return _this.fetchData(_this.$api.API_GetJxcBuyOrder2ReturnBillData, {
                sid,
            }).then(res => {
                _this.formData = res.data || {};
                let dataList = clothing.transferDetailList(_this.setting, _this.formData.detail_list, _this.tableOptions.columns);
                _this.initDataList(dataList);
            }).catch(() => {
            });
        },
        initDataList(detail_list) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(_this.dataList)) {
                list = _this.dataList.map(item => $.extend({}, item));
            }
            list = list.concat(detail_list || []);
            _this.dataList = _this.resetIndex(list);
        },
        initData(sid) {
            const _this = this;
            _this.dataList = [];
            return _this.fetchData(_this.$api.API_GetJxcBuyReturnBillBySid, {
                sid,
            }).then(result => {
                let resData = result.data || {};
                let dataList = clothing.transferDetailList(_this.setting, resData.detail_list, _this.tableOptions.columns);
                _this.formData = resData;
                _this.dataList = _this.resetIndex(dataList);
                _this.oldCode = resData.code;
            }).catch(() => {
            });
        },
        generateCode() {
            const _this = this;
            if (_this.$utils.isEmpty(_this.formData.supplier_sid)) {
                return;
            }
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: 'jxc_buy_return_bill',
                related_party_sid: _this.formData.supplier_sid,
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.buyReturnBillForm) {
                    _this.$refs.buyReturnBillForm.clearValidate('code');
                }
            });
        },
        rewriteChangeRow({ row, column }) {
            const _this = this;
            column = Object.assign({}, column, column.params)
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                _this.$set(row, column.prop, _this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double));
            }
            if (column.editRender && column.editRender.integer) {
                _this.$set(row, column.prop, _this.$XEUtils.IntInput(row[column.prop]));
            }
            if (column.prop === 'unit_name') {
                const goodsPrice = (row.price_list || []).find(item => item.unit_name === row[column.prop]);
                if (goodsPrice) {
                    _this.$set(row, "price", goodsPrice.buy_price);
                    _this.$set(row, "unit_qty", goodsPrice.qty);
                }
                _this.calcAmount(row);
                return;
            }
            if (['price', 'qty'].includes(column.prop)) {
                _this.calcAmount(row);
            }
        },
        calcAmount(row) {
            const _this = this;
            if (_this.$utils.isNotEmpty(row.qty) && _this.$utils.isNotEmpty(row.unit_qty)) {
                _this.$set(row, "qty4base", _this.$utils.accMul2Fixed(row.qty, row.unit_qty, 3));
            }
            if (_this.$utils.isNotEmpty(row.qty) && _this.$utils.isNotEmpty(row.price)) {
                let amount = _this.$utils.accMul(row.qty, row.price);
                _this.$set(row, "amount", amount);
            }
        },
        handleSupplierEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined') {
                _this.formData = $.extend({}, _this.formData, {
                    delivery_mode: event.data ? event.data.delivery_mode : '',
                    supplier_sid: event.value,
                    supplier_name: event.data ? event.data.name : '',
                    supplier_contract_name: event.data ? event.data.linker_name : '',
                    supplier_contract_phone: event.data ? event.data.linker_mobile : '',
                });
                if (_this.$utils.isNotEmpty(event.value)) {
                    if (_this.isEditFlag) {
                        _this.generateCode();
                    }
                    return;
                }
            }
            if (_this.isEditFlag) {
                return;
            }
            _this.formData = $.extend({}, _this.formData, {
                supplier_sid: '',
                supplier_name: '',
                supplier_contract_name: '',
                supplier_contract_phone: '',
            });
        },
        handleSelectBuyOrder() {
            const _this = this;
            if (_this.$utils.isEmpty(_this.formData.supplier_sid)) {
                _this.$message.error('请选择供应商');
                return;
            }
            let selected_list = (_this.dataList || []).map(item => item.buy_detail_sid);
            if (clothing.isClothing(_this.setting)) {
                selected_list = [];
                (_this.dataList || []).forEach(item => {
                    let presetBuyMap = item.preset_buy_map || {};
                    Object.keys(presetBuyMap).forEach(key => {
                        if (_this.$utils.isNotEmpty(presetBuyMap[key])) {
                            let values = presetBuyMap[key].split('_');
                            if (values.length === 2 && selected_list.indexOf(values[1]) === -1) {
                                selected_list.push(values[1]);
                            }
                        }
                    });
                });
            }
            _this.$dialog({
                title: '选择采购订单',
                width: '1000px',
                component: {
                    value: SelectBuyOrderDetail,
                    props: {
                        data: {
                            supplier_sid: _this.formData.supplier_sid,
                            selected_list,
                        },
                    },
                },
                confirmBtn: {
                    type: 'primary',
                    text: '确定',
                    loading: true,
                    click (dialog, { component }) {
                        component && typeof component.confirm === 'function' && component.confirm({
                            _component: _this,
                        });
                    },
                },
            });
        },
        calcShouldReturnAmount() {
            const _this = this;
            let totalAmount = 0;
            if (_this.$utils.isEmpty(_this.formData.free_shipping) || _this.formData.free_shipping === 0) {
                if (_this.$utils.isNotEmpty(_this.formData.real_freight) && !isNaN(Number(_this.formData.real_freight))) {
                    totalAmount = _this.$utils.accAdd(totalAmount, Number(_this.formData.real_freight));
                }
            }
            let filter = _this.dataList.filter(item => _this.$utils.isNotEmpty(item.amount));
            if (_this.$utils.isNotEmptyList(filter)) {
                filter.forEach(item => {
                    totalAmount = _this.$utils.accAdd(totalAmount, item.amount);
                });
            }
            if (_this.$utils.isNotEmpty(_this.formData.ignore_amount) && !isNaN(Number(_this.formData.ignore_amount))) {
                totalAmount = _this.$utils.accSubtr(totalAmount, Number(_this.formData.ignore_amount));
            }
            if (Number(totalAmount) < 0) {
                totalAmount = 0;
            }
            _this.formData = $.extend({}, _this.formData, {
                should_return_amount: totalAmount,
            });
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('buyReturnBillForm');
            if (!valid) {
                return false;
            }
            if (_this.formTableRef) {
                const errMap = await _this.formTableRef.validate(true);
                if (errMap) {
                    return false;
                }
            }
            let dataList = _this.dataList.filter(item => $.extend({}, item));
            if (!_this.$utils.isNotEmptyList(dataList)) {
                _this.$message.error('退货明细不能为空');
                return false;
            }
            dataList = clothing.procSubData(_this.setting, dataList);
            let subData = $.extend({}, _this.formData);
            subData.detail_list = dataList.map(item => {
                let obj = $.extend({}, item);
                obj.sn = item._index + 1;
                delete obj.amount;
                return obj;
            });
            let amountFieldList = ['pre_freight', 'real_freight', 'ignore_amount', 'return_amount'];
            amountFieldList.forEach(field => {
                if (_this.$utils.isNotEmpty(subData[field])) {
                    let value = Number(subData[field]);
                    subData[field] = isNaN(value) ? '' : value;
                }
            });
            return _this.fetchData(_this.$api.API_SaveJxcBuyReturnBill, subData).then(() => {
                _this.$message.success('保存成功！');
                if (!_this.dialog) {
                    _this.toBack(true);
                }
                return true;
            }).catch(() => {
                return false;
            });
        },
        toBack(refresh) {
            if (this.buy) {
                this.back('/jxcBuyOrder', refresh ? 'refreshJxcBuyOrder' : undefined);
                return;
            }
            this.back('/jxcBuyReturnBill', refresh ? 'refreshJxcBuyReturnBill' : undefined);
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.buy_return_bill_form_container {
    width: 100%;
    height: 100%;

    /deep/.el-checkbox {
        line-height: 1;
    }

    /deep/.card_content {
        position: relative;

        .btn_container {
            position: absolute;
            left: 0;
            top: -30px;
        }
    }

    .card-foot {
        gap: 120px;
        justify-content: center;

        .el-button {
            width: 120px;
        }
    }
}
</style>
